package com.tang.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.tang.mapper.UserMapper;
import com.tang.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import org.springframework.validation.support.BindingAwareConcurrentModel;
import org.springframework.web.bind.annotation.RestController;

import javax.sql.DataSource;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * @Author Tom
 * @ClassName SecurityConfig
 * @Date 2022/2/26 20:57
 */
@Service
public class SecurityConfig implements UserDetailsService {
 @Autowired
 private UserMapper userMapper;
 @Autowired
 private DataSource dataSource;
private User user;

 @Override
 public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
  //查询条件，用户名
  QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
  userQueryWrapper.eq("username", username);
  user = userMapper.selectOne(userQueryWrapper);

  if (user==null){

   throw new UsernameNotFoundException("用户名不存在");
  }

  //System.out.println("登陆成功");
  List<GrantedAuthority> role = AuthorityUtils.commaSeparatedStringToAuthorityList("admin");
  return new org.springframework.security.core.userdetails.User(user.getUsername(),new BCryptPasswordEncoder().encode(user.getPassword()),role);
 }

 @Bean
 PasswordEncoder password(){
  return new BCryptPasswordEncoder();
 }
 @Bean
 public PersistentTokenRepository getPersistentTokenRepository(){
  JdbcTokenRepositoryImpl jtr = new JdbcTokenRepositoryImpl();
  jtr.setDataSource(dataSource);
  System.out.println(dataSource.getClass());
//  jtr.setCreateTableOnStartup(true);
  return jtr;
 }
}
    